package com.tingyun.sign.pics.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.networkbench.base.util.security.MD5;
import com.tingyun.sign.core.entity.ScActivityBean;
import com.tingyun.sign.core.entity.ScPicsBean;
import com.tingyun.sign.core.entity.ScUCompanyUserBean;
import com.tingyun.sign.core.repository.ActivityDao;
import com.tingyun.sign.core.repository.CompanyUserDao;
import com.tingyun.sign.core.repository.PicsDao;
import com.tingyun.sign.pics.bean.ScPicsDto;
import com.tingyun.sign.pics.service.PicsService;
import com.tingyun.sign.utils.Constants;
import com.tingyun.sign.utils.DateUtils;
import com.tingyun.sign.utils.MyAssert;
import com.tingyun.sign.utils.Page;

@Service("picsService")
public class PicsServiceImpl implements PicsService {
	private static Logger log = LoggerFactory.getLogger(PicsServiceImpl.class);

	@Value("${pic_url}")
	private String filePath;

	@PersistenceContext(name = "jpa")
	private EntityManager entityManager;
	@Autowired
	private PicsDao picsDao;;
	
	@Autowired
	private ActivityDao activityDao;
	
	@Autowired
	private CompanyUserDao companyUserDao;
	
	/**
	 * 上传图片，如果已经上传过，就删除就图片
	 */
	@Transactional
	@Override
	public Integer addFile(MultipartFile[] files, ScPicsBean bean) {
		MyAssert.notNull(files, "上传的图片为空");
		MyAssert.notNull(bean, "图片参数为空");
		MyAssert.notNull(bean.getCompanyUserId(), "参数[客户ID]为空");
		MyAssert.notNull(bean.getActivityId(), "参数[活动ID]为空");
		//如果已经存在图片，先删除老图片
		List<ScPicsBean> list = null;
		if(bean.getHasPics() != null && bean.getHasPics() == 1) {
			list = picsDao.findByAcIdAndUserId(bean.getActivityId(),bean.getCompanyUserId());
			picsDao.deleteByAcIdAndUserId(bean.getActivityId(),bean.getCompanyUserId());
		}
		Map<String, String> names = new HashMap<String, String>(files.length);
		for(MultipartFile file : files) {
			//校验文件后缀
			String end = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
			if(!Constants.picTypes.contains(end.toUpperCase())) {
				MyAssert.isTrue(false, "不支持的图片格式，支持格式："+Constants.picTypes.toString());
			}
			//生成新的唯一名称
			String code = System.currentTimeMillis()+DateUtils.randomString(10);
			String newName = MD5.encryptToHex(code)+"."+end;
			bean.setPicNewName(newName);
			names.put(file.getOriginalFilename(), newName);
			//插入数据库
			bean.setPicOldName(file.getOriginalFilename());
			picsDao.save(bean);
		}
		boolean saveFailed = false;
		//循环写文件
		for(MultipartFile file : files) {
			//设置新文件路径
			File newFile = new File(filePath+"\\"+names.get(file.getOriginalFilename()));
			try {
				//写到文件系统
				file.transferTo(newFile);
			} catch (Exception e) {
				e.printStackTrace();
				//如果保存失败，标记为失败
				saveFailed = true;
				MyAssert.isTrue(false,"上传图片文件失败，请稍后重试");
			} finally {
				//如果保存失败，则回滚前删除已保存的图片文件
				if(saveFailed) {
					for(MultipartFile f : files) {
						File newF = new File(filePath+"\\"+names.get(f.getOriginalFilename()));
						newF.delete();
					}
				}
			}
		}
		//删除老图片文件
		if(bean.getHasPics() != null && bean.getHasPics() == 1) {
			File f = null;
			for(ScPicsBean obj : list) {
				try {
					f = new File(filePath + "\\" + obj.getPicNewName());
					f.delete();
				} catch (Exception e) {
					log.error("旧图片删除失败");
				}
			}
		}
		return 1;
	}
	
	@Override
	public Page<ScPicsBean> findPicsPage(ScPicsBean bean) {
		//必填参数校验
		MyAssert.notNull(bean.getActivityId(), "参数[活动ID]为空");
		//分页查询
		Page<ScPicsBean> page = new Page<ScPicsBean>();
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<ScPicsBean> cq = cb.createQuery(ScPicsBean.class);
		Root<ScPicsBean>  root = cq.from(ScPicsBean.class);
		//整合查询条件
		List<Predicate> pres = new ArrayList<Predicate>();
		if(bean.getStartTime() != null) {
			pres.add(cb.greaterThanOrEqualTo(root.<Date>get("ctime"), bean.getStartTime()));
		}
		if(bean.getEndTime() != null) {
			pres.add(cb.lessThan(root.<Date>get("ctime"), DateUtils.addDay(bean.getEndTime(), 1)));
		}
		if(bean.getActivityId()!=null) {
			pres.add(cb.equal(root.get("activityId"), bean.getActivityId()));
		}		
		if(bean.getCompanyUserId()!=null) {
			pres.add(cb.equal(root.get("companyUserId"), bean.getCompanyUserId()));
		}
//		if(bean.getUserName()!=null) {
//			pres.add(cb.like(root.<String>get("userName"), "%"+bean.getUserName()+"%"));
//		}
//		if(bean.getCompanyName()!=null) {
//			pres.add(cb.like(root.<String>get("companyName"), "%"+bean.getCompanyName()+"%"));
//		}
		Predicate p = cb.and(pres.toArray(new Predicate[pres.size()]));
		cq.where(p);//and
		cq.orderBy(cb.desc(root.get("id")));//排序
		//执行查询
		TypedQuery<ScPicsBean> query = entityManager.createQuery(cq);
		query.setFirstResult(bean.getStart());
		query.setMaxResults(bean.getPageSize());
		List<ScPicsBean> list = query.getResultList();
		
		//查询活动区域、客户名
		if(list != null && list.size() > 0) {
			//查询活动
			List<Long> acIds = new ArrayList<Long>(list.size());
			for(ScPicsBean b : list) {
				acIds.add(b.getActivityId());
			}
			List<ScActivityBean> acs = (List<ScActivityBean>) activityDao.findByIds(acIds);
			Map<Long, String> nameMap = new HashMap<Long, String>(acs.size());
			for(ScActivityBean b : acs) {
				nameMap.put(b.getId(), b.getTopic());
			}
			//查询客户信息
			List<Long> userIds = new ArrayList<Long>(list.size());
			for(ScPicsBean b : list) {
				userIds.add(b.getCompanyUserId());
			}
			List<ScUCompanyUserBean> users = (List<ScUCompanyUserBean>) companyUserDao.findByIds(userIds);
			Map<Long, String> userMap = new HashMap<Long, String>(users.size());
			for(ScUCompanyUserBean b : users) {
				userMap.put(b.getId(), b.getUserName());
			}
			//设置活动名和客户名
			for(ScPicsBean b : list) {
				b.setActivityTopic(nameMap.get(b.getActivityId()));
				b.setCompanyUserName(userMap.get(b.getCompanyUserId()));
			}
		}
		
		page.setResultList(list);
		//查询总数
		page.setTotalCount(countPic(bean));
		return page;
	}
	/**
	 * 根据活动ID查询客户总数
	 * @param end 
	 * @param start 
	 */
	public Integer countPic(ScPicsBean bean) {
		String sql = "SELECT COUNT(ID) FROM Sc_PICS T WHERE T.activity_Id=?";
		Query query = entityManager.createNativeQuery(sql);
		query.setParameter(1, bean.getActivityId());
		return Integer.parseInt(query.getSingleResult().toString());
	}

}
